package com.eipc;

import java.util.ArrayList;

import org.androidpn.sdk.Constants;
import org.androidpn.sdk.XmppManager;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.eipc.event.OnFetchOtherFinishedListener;
import com.eipc.model.Game;
import com.eipc.model.Match;
import com.eipc.model.News;
import com.eipc.model.Player;
import com.eipc.model.PlayerGroup;
import com.eipc.model.Response;
import com.eipc.model.Score;
import com.eipc.model.SerInfoResponse;
import com.eipc.model.TEverydayAround;
import com.eipc.model.Weather;
import com.eipc.model.TEverydayAround.TEverydayGroup;
import com.eipc.model.TwoValue;
import com.eipc.util.DBHelper;
import com.eipc.util.HttpManager;
import com.eipc.util.JsonParse;
import com.eipc.util.MyLog;
import com.eipc.util.Tools;

/**
 * 每日对阵
 * @author x_liaolijun
 *
 * 2010-9-12 上午08:44:47
 *  
 * EverydatVsActivity
 *
 */
public class EverydayVsActivity extends CommonActivity implements OnClickListener {
	public final static String STATICS_START = "0";   //即将开始
	public final static String STATICS_DOING = "1";   //正在进行
	public final static String STATICS_ENDING = "2";   //刚刚结束
	public final static String STATICS_ENDED  = "3";   //已经结束
	public boolean isNotRef = true;
	
	private final static int INTERVAL = 8 ;
	
	/*
	 * 数字对应的数据
	 */
	public final static TwoValue[] DAYS_ENGLISH = new TwoValue[]{
		new TwoValue(9,"10/09 (D1)"), //1
		new TwoValue(10,"10/10 (D2)"), //2
		new TwoValue(11,"10/11 (D3)"), //3
		new TwoValue(12,"10/12 (D4)"), //4
		new TwoValue(13,"10/13 (D5)"), //5
		new TwoValue(14,"10/14 (D6)"), //6
		new TwoValue(15,"10/15 (D7)"), //7
		new TwoValue(16,"10/16 (D8)"), //8
		new TwoValue(17,"10/17 (D9)"), //9
	};
	
	/*
	 * 数字英文对应的数据
	 */
	public final static TwoValue[] DAYS_CHINESE = new TwoValue[]{
		new TwoValue(9,"十月九日  第一比赛日"), //1
		new TwoValue(10,"十月十日  第二比赛日"), //2
		new TwoValue(11,"十月十一日  第三比赛日"), //3
		new TwoValue(12,"十月十二日  第四比赛日"), //4
		new TwoValue(13,"十月十三日  第五比赛日"), //5
		new TwoValue(14,"十月十四日  第六比赛日"), //6
		new TwoValue(15,"十月十五日  第七比赛日"), //7
		new TwoValue(16,"十月十六日  第八比赛日"), //8
		new TwoValue(17,"十月十七日  第九比赛日"), //9
	};
	
	private ArrayList<TEverydayAround> mEverydayArounds;
	private LinearLayout mLayout;
	private TextView mPrevoius;
	private TextView mNext;
	private TextView mDate;
	private TwoValue[] DAYS;
	private int mCurNumber = 0;
	private TextView[] mTextViews = new TextView[9];
	private int[] mDays;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.everyday_vs);
		if(mLocale==LANGUAGE_CHINESE)
			DAYS = DAYS_CHINESE;
		else
			DAYS = DAYS_ENGLISH;
		initView();
	}
	
	@Override
	protected void initView() {
		super.initView();
		mBar.setOnRightClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new PollingMatchScoreTask().execute();
			}
		});
		mBar.setMiddleText(R.string.everday_vs); 
		mLayout = (LinearLayout)findViewById(R.id.layout);
		mPrevoius = (TextView)findViewById(R.id.tv_previous);
		mNext = (TextView)findViewById(R.id.tv_next);
		mDate = (TextView)findViewById(R.id.tv_date);
		mTextViews[0]= (TextView)findViewById(R.id.tv_one);
		mTextViews[0].setTag(DAYS[0]);
		mTextViews[0].setOnClickListener(this);
		mTextViews[1] = (TextView)findViewById(R.id.tv_two);
		mTextViews[1].setTag(DAYS[1]);
		mTextViews[1].setOnClickListener(this);
		mTextViews[2] = (TextView)findViewById(R.id.tv_three);
		mTextViews[2].setTag(DAYS[2]);
		mTextViews[2].setOnClickListener(this);
		mTextViews[3] = (TextView)findViewById(R.id.tv_four);
		mTextViews[3].setTag(DAYS[3]);
		mTextViews[3].setOnClickListener(this);
		mTextViews[4] = (TextView)findViewById(R.id.tv_five);
		mTextViews[4].setTag(DAYS[4]);
		mTextViews[4].setOnClickListener(this);
		mTextViews[5] = (TextView)findViewById(R.id.tv_six);
		mTextViews[5].setTag(DAYS[5]);
		mTextViews[5].setOnClickListener(this);
		mTextViews[6] = (TextView)findViewById(R.id.tv_seven);
		mTextViews[6].setTag(DAYS[6]);
		mTextViews[6].setOnClickListener(this);
		mTextViews[7] = (TextView)findViewById(R.id.tv_eight);
		mTextViews[7].setTag(DAYS[7]);
		mTextViews[7].setOnClickListener(this);
		mTextViews[8] = (TextView)findViewById(R.id.tv_nine);
		mTextViews[8].setTag(DAYS[8]);
		mTextViews[8].setOnClickListener(this);
		
		//TODO 这里需要根据哪天求出这个1的参数
		updateView();
		
		mPrevoius.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(mCurNumber-2>=0){
					if(mTextViews[mCurNumber-2].isEnabled()){
						getData(DAYS[mCurNumber-2]);
					}
				}
			}
		});
		
		mNext.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(mCurNumber<9){
					if(mTextViews[mCurNumber].isEnabled()){
						getData(DAYS[mCurNumber]);
					}
				}
			}
		});
	}
	
	@Override
	public void onClick(View v) {
		getData((TwoValue)v.getTag());
	}
	
	/*
	 * 根据数字拿到那天的数据(1--9)
	 * @param number
	 */
	private void getData(TwoValue two){
		//
		if(two.one-INTERVAL!=mCurNumber){
			mDate.setText(two.two);
			mEverydayArounds = mDB.getEverydayMatch(two.one);
			toggleTextView(two.one-INTERVAL);
			mCurNumber = two.one-INTERVAL;
			changeView();
		}
	}
	
	@Override
	protected void updateView(){
		super.updateView();
		mDays = mDB.getAllMatchDay();
		int len = 0;
		if(mDays!=null){
			if(mCurNumber==0){
				getData(DAYS[0]);
			}
			else{
				getData(DAYS[mCurNumber-1]);
			}
			len = mDays.length;
			boolean flag = false;
			for(int i=0;i<9;i++){
				for(int j=0;j<len;j++){
					if(mDays[j]==DAYS[i].one){
						flag = true;
					}
				}
				if(!flag){
					mTextViews[i].setEnabled(false);
					mTextViews[i].setBackgroundResource(R.drawable.everyday_table_disable_text_color);
				}
				flag = false;
			}
		}
		else{
			for(int j=0;j<9;j++){
				mTextViews[j].setEnabled(false);
				mTextViews[j].setBackgroundResource(R.drawable.everyday_table_disable_text_color);
			}
		}
	}
	
	/*
	 * 改变view
	 */
	private void changeView(){ 
		mLayout.removeAllViews();
		if(mEverydayArounds!=null){
			View view = null;
			TextView one = null;
			TextView two = null;
			ListView list = null;
			for(TEverydayAround around : mEverydayArounds){
				createView(around);
			}
		}
	}
	
	private void createView(TEverydayAround around){
		View view = mInflater.inflate(R.layout.everyday_head, null);
		TextView tv = (TextView)view.findViewById(R.id.text1);
		tv.setText(around.name);
		tv = (TextView)view.findViewById(R.id.text2);
		tv.setText(around.beginTime);
		mLayout.addView(view);
		try{
			if(around.matches!=null && around.matches.size()>0){
				int len = around.matches.size();
				TEverydayAround.TEverydayMatch match = null;
				for(int i=0;i<len;i++){
					view = mInflater.inflate(R.layout.erveryday_item, null);
					if(i%2==0){
						view.setBackgroundResource(android.R.color.white);
					}
					else{
						view.setBackgroundResource(R.drawable.player);
					}
					match = around.matches.get(i);
					tv = (TextView)view.findViewById(R.id.text1);
					tv.setText(match.matchTime);
					if("no".equals(match.isGroup.toLowerCase())){//单打
						tv = (TextView)view.findViewById(R.id.text2);
						tv.setTag(match.playerA);
						tv.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								showPlayerDialog((Player)v.getTag());
							}
						});
						if(mLocale==LANGUAGE_CHINESE)
							tv.setText(Tools.removeClub(getString(R.string.everyday_single,match.playerA.enSname,match.playerA.seedNumber)));
						else
							tv.setText(Tools.removeClub(getString(R.string.everyday_single,match.playerA.enSname,match.playerA.seedNumber)));
						tv = (TextView)view.findViewById(R.id.tv_country);
						if(mLocale==LANGUAGE_CHINESE){
							tv.setText(match.playerA.enCountry);
						}
						else{
							tv.setText(match.playerA.enCountry);
						}
						tv = (TextView)view.findViewById(R.id.text4);
						tv.setTag(match.playerB);
						tv.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								showPlayerDialog((Player)v.getTag());
							}
						});
						if(mLocale==LANGUAGE_CHINESE)
							tv.setText(Tools.removeClub(getString(R.string.everyday_single,match.playerB.enSname,match.playerB.seedNumber)));
						else
							tv.setText(Tools.removeClub(getString(R.string.everyday_single,match.playerB.enSname,match.playerB.seedNumber)));
						tv = (TextView)view.findViewById(R.id.tv_country2);
						if(mLocale==LANGUAGE_CHINESE){
							tv.setText(match.playerB.enCountry);
						}
						else{
							tv.setText(match.playerB.enCountry);
						}
//						if(STATICS_ENDED.equals(match.statics)){//已经结束
							if(match.winner!=null && !"".equals(match.winner) &&! String.valueOf(match.playerA.playerId).equals(match.winner)){
								Player a = match.playerA;
								match.playerA = match.playerB;
								match.playerB = a;
								
							}
							if(match.winner!=null && !"".equals(match.winner) )
							{
							tv = (TextView)view.findViewById(R.id.text3);
							tv.setText(R.string.everyday_win);
							}
							
							tv = (TextView)view.findViewById(R.id.text5);
							if(match.playerRetail!=null && match.playerRetail.equals(String.valueOf(match.playerB.playerId))){//伤退
								tv.setText(getString(R.string.everyday_result, match.score,getString(R.string.everyday_exit)));
							}
							else{
								tv.setText(getString(R.string.everyday_result, match.score,""));
							}
//						}
					}
					else{
						tv = (TextView)view.findViewById(R.id.text2);
						tv.setTag(match.groupA.playerA);
						tv.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								showPlayerDialog((Player)v.getTag());
							}
						});
						if(mLocale==LANGUAGE_CHINESE)
							tv.setText(Tools.removeClub(getString(R.string.everyday_double,match.groupA.playerA.enSname)));
						else
							tv.setText(Tools.removeClub(getString(R.string.everyday_double,match.groupA.playerA.enSname)));
						tv = (TextView)view.findViewById(R.id.tv_country);
						if(mLocale==LANGUAGE_CHINESE){
							tv.setText(match.groupA.playerA.enCountry);
						}
						else{
							tv.setText(match.groupA.playerA.enCountry);
						}
						tv = (TextView)view.findViewById(R.id.text22);
						tv.setVisibility(View.VISIBLE);
						tv.setTag(match.groupA.playerB);
						tv.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								showPlayerDialog((Player)v.getTag());
							}
						});
						if(mLocale==LANGUAGE_CHINESE)
							tv.setText(Tools.removeClub(getString(R.string.everyday_double,match.groupA.playerB.enSname)));
						else
							tv.setText(Tools.removeClub(getString(R.string.everyday_double,match.groupA.playerB.enSname)));
						tv = (TextView)view.findViewById(R.id.line1);
						tv.setVisibility(View.VISIBLE);
						tv = (TextView)view.findViewById(R.id.tv_country11);
						tv.setVisibility(View.VISIBLE);
						if(mLocale==LANGUAGE_CHINESE){
							tv.setText(getString(R.string.everyday_double2, match.groupA.playerB.enCountry,match.groupA.playerB.seedNumber));
						}
						else{
							tv.setText(getString(R.string.everyday_double2, match.groupA.playerB.enCountry,match.groupA.playerB.seedNumber));
						}
						tv = (TextView)view.findViewById(R.id.text4);
						tv.setTag(match.groupB.playerA);
						tv.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								showPlayerDialog((Player)v.getTag());
							}
						});
						if(mLocale==LANGUAGE_CHINESE)
							tv.setText(Tools.removeClub(getString(R.string.everyday_double,match.groupB.playerA.enSname)));
						else
							tv.setText(Tools.removeClub(getString(R.string.everyday_double,match.groupB.playerA.enSname)));
						tv = (TextView)view.findViewById(R.id.tv_country2);
						if(mLocale==LANGUAGE_CHINESE){
							tv.setText(match.groupB.playerA.enCountry);
						}
						else{
							tv.setText(match.groupB.playerA.enCountry);
						}
						tv = (TextView)view.findViewById(R.id.line2);
						tv.setVisibility(View.VISIBLE);
						tv = (TextView)view.findViewById(R.id.text42);
						tv.setVisibility(View.VISIBLE);
						tv.setTag(match.groupB.playerB);
						tv.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								showPlayerDialog((Player)v.getTag());
							}
						});
						if(mLocale==LANGUAGE_CHINESE)
							tv.setText(Html.fromHtml(Tools.removeClub(getString(R.string.everyday_double,match.groupB.playerB.enSname))));
						else
							tv.setText(Html.fromHtml(Tools.removeClub(getString(R.string.everyday_double,match.groupB.playerB.enSname))));
						tv = (TextView)view.findViewById(R.id.tv_country22);
						tv.setVisibility(View.VISIBLE);
						if(mLocale==LANGUAGE_CHINESE){
							tv.setText(getString(R.string.everyday_double2, match.groupB.playerB.enCountry,match.groupA.playerB.seedNumber));
						}
						else{
							tv.setText(getString(R.string.everyday_double2, match.groupB.playerB.enCountry,match.groupA.playerB.seedNumber));
						}
//						if(STATICS_ENDED.equals(match.statics)){//已经结束
							if(match.groupWinner!=null && !"".equals(match.groupWinner) &&! match.groupA.equals(match.groupWinner)){
								TEverydayGroup a = match.groupA;
								match.groupA = match.groupB;
								match.groupB = a;
								
							}
							
							if(match.groupWinner!=null && !"".equals(match.winner))
							{
								tv = (TextView)view.findViewById(R.id.text3);
								tv.setText(R.string.everyday_win);
							}
							
							tv = (TextView)view.findViewById(R.id.text5);
							if(match.groupRetail!=null && (match.groupRetail.equals(String.valueOf(match.groupA.playerA.playerId)) || match.groupRetail.equals(String.valueOf(match.groupA.playerB.playerId)))){//伤退
								tv.setText(getString(R.string.everyday_result, match.score,getString(R.string.everyday_exit)));
							}
							else{
								tv.setText(getString(R.string.everyday_result, match.score,""));
							}
//						}
					}
					mLayout.addView(view);
				}
			}
		}
		catch (Exception e) {
			Log.w("EverdayVsActivity", e);
		}
	}
	
	/*
	 * 改变头部数字的背景
	 */
	private void toggleTextView(int number){
		if(mCurNumber!=number){
			if(mCurNumber==0) mCurNumber = 1;
			mTextViews[mCurNumber-1].setBackgroundResource(android.R.color.white);
			mTextViews[number-1].setBackgroundResource(R.drawable.everyday_table_text_check_color);
		}
	}
	
	class PollingMatchScoreTask extends CommonTask<Void>{
		public PollingMatchScoreTask(){
			super(EverydayVsActivity.this);
		}
		
		private SerInfoResponse matchSir;
		private SerInfoResponse scoreSir;
		private boolean isOk = false;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			//TODO 删除数据
			mDB.deleteAll(DBHelper.TB_MATCH);
			mDB.deleteAll(DBHelper.TB_SCORE);
		}
		@Override
		protected Void doInBackground(Void... params){
			isNotRef = false;
			Log.i("--"+this.getClass().getName(),"------------------PollingMatchScoreTask------------------ right : ");
			try {
				SharedPreferences sdkPreferences = getSharedPreferences(Constants.SDK_PREFERENCES, Context.MODE_PRIVATE);
				String mobileID = sdkPreferences.getString(Constants.XMPP_USERNAME,"");
				matchSir = HttpManager.loadSerInfo(getString(R.string.url_load_serinfo),mobileID,Constants.MACH,Constants.LOAD_MODEL_MATCH);
				scoreSir = HttpManager.loadSerInfo(getString(R.string.url_load_serinfo),mobileID,Constants.SCORE,Constants.LOAD_MODEL_SCORE);
				if(matchSir!=null&&scoreSir!=null){
	            	//TODO 刷新成功 等待 PUSH	
	            	try{mDB.insertMatch((Match[])matchSir.os);}catch(Exception e){mBuilder.setMessage(R.string.status_save_match_failed).setNegativeButton(R.string.btn_close, null).show();}
	            	try{mDB.insertScore((Score[])scoreSir.os);}catch(Exception e){mBuilder.setMessage(R.string.status_save_score_failed).setNegativeButton(R.string.btn_close, null).show();}
	            	new FetchOtherTask(EverydayVsActivity.this, mDB, new OnFetchOtherFinishedListener() {	
						@Override
						public void OnFinished(ArrayList<News> news, Game game, Weather weather) {
							if(news!=null && news.size()>0){
								for(News n : news){
									mInfos.addView(getNewsView(n));
									mInfos.startFlipping();
								}
							}
							else{
								mInfos.addView( mInflater.inflate(R.layout.news_item, null));
							}
							mBottomBar.setGame(game);
							mBottomBar.setWeather(weather);
							mBottomBar.startFlipper();
						}
					}).execute(mLocale);
	            	isOk = true;
	            }
			} catch (Exception e) {
				MyLog.error(FetchConsultService.class,"",e);
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			isNotRef = true;
			if(!isOk){
				mBuilder.setMessage(R.string.status_connect_failed).setNegativeButton(R.string.btn_close, null).show();
			}else{
				updateView();
			}
		}
		
	}
}
